package com.tzl.mfwl;

import java.io.File;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 * 清理maven仓库下载失败文件的一个工具
 *
 * @author tang zhilei
 * @date 2022/07/26 13:37
 */
public class MavenClean {

    /**
     * 启动时传递进入maven本地仓库的地址，默认 args[0]
     *
     * @param args
     */
    public static void main(String[] args) {
        clear(getMavenRepoLocation(args));
    }

    /**
     * 清理操作
     *
     * @param repoFile
     */
    private static void clear(File repoFile) {
        Queue<File> queue = new LinkedList<>();
        queue.offer(repoFile);
        while (!queue.isEmpty()) {
            File file = queue.poll();
            if (file.isDirectory()) {
                File[] children = file.listFiles();
                if (children != null && children.length > 0) {
                    for (File f : children) {
                        queue.offer(f);
                    }
                } else {
                    // 将空目录也一起删除了
                    if (file.delete()) {
                        System.out.println(
                                "found empty directory '" + file.getName() + "', delete!!!");
                    }
                }
            } else {
                // 后缀名为 lastUpdated的，删除
                String fileName = file.getName();
                if (fileName.endsWith("lastUpdated")) {
                    if (file.delete()) {
                        System.out.println("found file '" + fileName + "', delete!!");
                    }
                }
            }
        }
    }

    /**
     * 处理maven仓库地址信息
     *
     * @param args
     * @return maven仓库地址对应的file对象
     */
    private static File getMavenRepoLocation(String[] args) {
        String mavenRepoLocation = null;
        if (args.length > 0) {
            mavenRepoLocation = args[0];
        }
        // 当启动时传入的地址值为空，则需要手动输入地址
        Scanner scanner = new Scanner(System.in);
        File file = null;
        while (true) {
            if (isEmpty(mavenRepoLocation)) {
                System.out.println("请输入maven仓库的地址:");
                mavenRepoLocation = scanner.nextLine();
            }
            try {
                file = new File(mavenRepoLocation);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (file != null && file.isDirectory()) {
                break;
            } else {
                mavenRepoLocation = null;
            }
        }
        scanner.close();
        return file;
    }

    /**
     * 判断字符串是否是null或者空字符串
     *
     * @param str 字符串
     * @return
     */
    private static boolean isEmpty(String str) {
        return str == null || "".equals(str);
    }
}
